﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp_Binding.DataValidation
{
    public class ValidationDataSource : IDataErrorInfo
    {

        [StringLength(20)]
        [DisplayName("地址")]
        [Required(ErrorMessage = "请输入现场地址！")]
        public string Address { get; set; } = string.Empty;

        [Range(1,10,ErrorMessage ="患者人数必须再0至10之间！")]
        public int PatientCount { get; set; }


        public string Error { get; set; } = string.Empty;
        public string this[string columnName]
        {
            get
            {
                PropertyInfo? propertyInfo = this.GetType().GetProperty(columnName);
                if (propertyInfo == null)
                    throw new ArgumentException();
                DisplayNameAttribute? displayNameAttribute = null;
                if (propertyInfo.IsDefined(typeof(DisplayNameAttribute)))
                    displayNameAttribute = propertyInfo.GetCustomAttribute<DisplayNameAttribute>();

                string _value = propertyInfo.PropertyType == typeof(String) ? propertyInfo.GetValue(this)?.ToString() ?? "" : string.Empty;
                if (propertyInfo.IsDefined(typeof(RequiredAttribute)) && string.IsNullOrEmpty(_value))
                {
                    RequiredAttribute? requiredAttribute = propertyInfo.GetCustomAttribute<RequiredAttribute>();
                    return requiredAttribute != null ? requiredAttribute.ErrorMessage! : $"{displayNameAttribute!.DisplayName}是必填项！";
                }

                if (propertyInfo.IsDefined(typeof(StringLengthAttribute)))
                {
                    
                    StringLengthAttribute? stringLengthAttribute = propertyInfo.GetCustomAttribute(typeof(StringLengthAttribute)) as StringLengthAttribute;
                    if (stringLengthAttribute != null && _value.Length >= stringLengthAttribute.MaximumLength)
                    {
                        return $"{displayNameAttribute!.DisplayName}的长度不能超过{stringLengthAttribute.MaximumLength}个字符！";
                    }
                }

                if (propertyInfo.IsDefined(typeof(RangeAttribute)))
                { 
                    RangeAttribute? rangeAttribute = propertyInfo.GetCustomAttribute<RangeAttribute>();
                    if (rangeAttribute != null)
                    {
                        int _int_value = Convert.ToInt32(propertyInfo.GetValue(this));
                        if (_int_value < Convert.ToInt32(rangeAttribute.Minimum) || _int_value >= Convert.ToInt32(rangeAttribute.Maximum))
                            return rangeAttribute.ErrorMessage!;
                    }
                }
                return "";
            }
        }
    }
}
